<script setup lang="ts">
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import CustomNavbar from './componets/CustomNavbar.vue'
import CategoryPanel from './componets/CategoryPanel.vue'
import HotPanel from './componets/HotPanel.vue'
import PageSkeleton from './componets/PageSkeleton.vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/component'
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 轮播图
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

// 前台小程序
const cateGoryList = ref<CategoryItem[]>([])
const getHomeCategoryList = async () => {
  const res = await getHomeCategoryAPI()
  cateGoryList.value = res.result
}

// 特惠推荐
const homeHotList = ref<HotItem[]>([])
const getHomeHotList = async () => {
  const res = await getHomeHotAPI()
  homeHotList.value = res.result
  console.log('hotList', res)
}

// 滚动触底事件
const scrolltolower = () => {
  guessRef.value?.getMore()
}
// 创建猜你喜欢组件的实例
const guessRef = ref<XtxGuessInstance>()

// 页面加载中标记
const isLoading = ref(false)
// 页面加载
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryList(), getHomeHotList()])
  isLoading.value = false
})

// 下拉刷新
const refresherrefresh = async () => {
  triggered.value = true
  // 重置猜你喜欢数据
  guessRef.value?.resetData()
  const res = await Promise.all([
    getHomeBannerData(),
    getHomeCategoryList(),
    getHomeHotList(),
    guessRef.value?.getMore(),
  ])
  console.log('all', res)

  console.log('刷新')
  triggered.value = false
}
// 设置刷新状态
const triggered = ref(false)
</script>

<template>
  <CustomNavbar></CustomNavbar>

  <PageSkeleton v-if="isLoading"></PageSkeleton>
  <!-- 滚动容器 -->
  <template v-else>
    <scroll-view
      refresher-enabled
      enable-back-to-top
      :refresher-triggered="triggered"
      @refresherrefresh="refresherrefresh"
      scroll-y
      class="scroll-view"
      @scrolltolower="scrolltolower"
    >
      <XtxSwiper :list="bannerList"></XtxSwiper>
      <CategoryPanel :list="cateGoryList"></CategoryPanel>
      <HotPanel :list="homeHotList"></HotPanel>
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef"> </XtxGuess>
    </scroll-view>
  </template>
</template>

<style lang="scss">
//
page {
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;
  height: 100%;
}
scroll-view {
  flex: 1;
}
</style>
